<route lang="jsonc" type="page">
{
"style": {
// 'custom' 表示开启自定义导航栏，默认 'default'
// "navigationStyle": "custom",
"navigationBarTitleText": "我的"
}
}
</route>

<script lang="ts" setup>
import type { OssDTO } from '@/api/types/common'
import type { UserProfileUpdateDto } from '@/api/user'
import { storeToRefs } from 'pinia'
import { updateAvatar, updateNickname, updateProfile } from '@/api/user'
import { LOGIN_PAGE } from '@/router/config'
import { useUserStore } from '@/store'
import { useTokenStore } from '@/store/token'
import { useUpload } from '@/utils/uploadFile'

const userStore = useUserStore()
const tokenStore = useTokenStore()
// 使用storeToRefs解构userInfo
const { userInfo } = storeToRefs(userStore)

// 编辑用户信息状态
const showEditModal = ref(false)
const editForm = ref<UserProfileUpdateDto>({
  nickName: '',
  phonenumber: '',
  sex: '',
  email: '',
})

// 功能菜单配置
const menuItems = [
  {
    icon: '⚙️',
    title: '设置',
    desc: '个人设置',
    action: () => {
      uni.showToast({ title: '功能开发中', icon: 'none' })
    },
  },
]

// #ifndef MP-WEIXIN
// 上传头像
const { run: uploadAvatar } = useUpload<OssDTO>(
  import.meta.env.VITE_UPLOAD_BASEURL,
  {},
  {
    onSuccess: async (res) => {
      console.log('h5头像上传成功', res)
      try {
        // 调用后端API更新用户头像
        await updateAvatar(res.ossId)
        // 更新本地状态
        useUserStore().setUserAvatar(res.url)
        uni.showToast({ title: '头像更新成功', icon: 'success' })
      }
      catch (error) {
        console.error('头像更新失败:', error)
        uni.showToast({ title: '头像更新失败', icon: 'none' })
      }
    },
  },
)
// #endif

// 微信小程序下登录
async function handleLogin() {
  // #ifdef MP-WEIXIN

  // 微信登录
  await tokenStore.wxLogin()
  // #endif
  // #ifndef MP-WEIXIN
  uni.navigateTo({ url: LOGIN_PAGE })
  // #endif
}

// #ifdef MP-WEIXIN

// 微信小程序下选择头像事件
function onChooseAvatar(e: any) {
  console.log('选择头像', e.detail)
  const { avatarUrl } = e.detail
  const { run } = useUpload<OssDTO>(
    import.meta.env.VITE_UPLOAD_BASEURL,
    {},
    {
      onSuccess: async (res) => {
        console.log('wx头像上传成功', res)
        try {
          // 调用后端API更新用户头像
          await updateAvatar(res.ossId)
          // 更新本地状态
          useUserStore().setUserAvatar(res.url)
          uni.showToast({ title: '头像更新成功', icon: 'success' })
        }
        catch (error) {
          console.error('头像更新失败:', error)
          uni.showToast({ title: '头像更新失败', icon: 'none' })
        }
      },
    },
    avatarUrl,
  )
  run()
}

// #endif
// #ifdef MP-WEIXIN
// 微信小程序下更新昵称
async function updateUserNickname(e: any) {
  const nickname = e.detail.value
  if (!nickname || nickname.length === 0) {
    uni.showToast({ title: '昵称不能为空', icon: 'none' })
    return
  }

  if (nickname.length > 30) {
    uni.showToast({ title: '昵称长度不能超过30个字符', icon: 'none' })
    return
  }

  try {
    await updateNickname(nickname)
    userInfo.value.nickname = nickname
    uni.showToast({ title: '昵称更新成功', icon: 'success' })
  }
  catch (error) {
    console.error('昵称更新失败:', error)
    uni.showToast({ title: '昵称更新失败', icon: 'none' })
  }
}

// #endif

// #ifndef MP-WEIXIN
// 打开编辑用户信息模态框
function openEditModal() {
  editForm.value.nickName = userInfo.value.nickname || ''
  editForm.value.phonenumber = userInfo.value.phonenumber || ''
  editForm.value.sex = userInfo.value.sex || ''
  editForm.value.email = userInfo.value.email || ''
  showEditModal.value = true
}

// 保存用户信息
async function saveUserProfile() {
  try {
    await updateProfile(editForm.value)
    // 更新本地状态
    if (editForm.value.nickName) {
      userInfo.value.nickname = editForm.value.nickName
    }
    showEditModal.value = false
    uni.showToast({ title: '信息更新成功', icon: 'success' })
  }
  catch (error) {
    console.error('用户信息更新失败:', error)
    uni.showToast({ title: '信息更新失败', icon: 'none' })
  }
}

// 关闭编辑模态框
function closeEditModal() {
  showEditModal.value = false
}

// #endif

// 退出登录
function handleLogout() {
  uni.showModal({
    title: '提示',
    content: '确定要退出登录吗？',
    success: (res) => {
      if (res.confirm) {
        // 清空用户信息
        useTokenStore().logout()
        // 执行退出登录逻辑
        uni.showToast({
          title: '退出登录成功',
          icon: 'success',
        })
        // #ifdef MP-WEIXIN
        // 微信小程序，去首页
        // uni.reLaunch({ url: '/pages/index/index' })
        // #endif
        // #ifndef MP-WEIXIN
        // 非微信小程序，去登录页
        uni.navigateTo({ url: LOGIN_PAGE })
        // #endif
      }
    },
  })
}
</script>

<template>
  <view class="profile-container">
    <!-- 未登录状态 -->
    <view v-if="!tokenStore.hasLogin" class="login-prompt-container">
      <!-- 主要内容区域 -->
      <view class="login-content">
        <!-- 头像区域 -->
        <view class="user-avatar-section">
          <view class="avatar-wrapper">
            <image :src="userInfo.avatar" mode="scaleToFill" class="avatar-img" />
          </view>
          <view class="user-info">
            <text class="username-placeholder">请输入昵称</text>
            <text class="user-desc">登录后完善个人信息</text>
          </view>
        </view>

        <!-- 功能菜单区域 -->
        <view class="menu-list">
          <view class="menu-item-disabled">
            <view class="menu-left">
              <view class="menu-icon">
                ⚙️
              </view>
              <text class="menu-title">设置</text>
            </view>
            <view class="menu-arrow">
              >
            </view>
          </view>
          <view class="menu-item-disabled">
            <view class="menu-left">
              <view class="menu-icon">
                📞
              </view>
              <text class="menu-title">联系客服</text>
            </view>
            <view class="menu-arrow">
              >
            </view>
          </view>
        </view>

        <!-- 登录按钮 -->
        <view class="login-button-container">
          <button type="primary" class="clean-login-btn" @click="handleLogin">
            立即登录
          </button>
        </view>
      </view>
    </view>

    <!-- 已登录状态 - 用户信息区域 -->
    <view v-else class="user-info-section">
      <!-- #ifdef MP-WEIXIN -->
      <button class="avatar-button" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
        <image :src="userInfo.avatar" mode="scaleToFill" class="h-full w-full" />
      </button>
      <!-- #endif -->
      <!-- #ifndef MP-WEIXIN -->
      <view class="avatar-wrapper" @click="uploadAvatar">
        <image :src="userInfo.avatar" mode="scaleToFill" class="h-full w-full" />
      </view>
      <!-- #endif -->
      <view class="user-details">
        <!-- #ifdef MP-WEIXIN -->
        <input
          v-model="userInfo.nickname"
          type="nickname"
          class="weui-input username-input"
          placeholder="请输入昵称"
          @blur="updateUserNickname"
        >
        <!-- #endif -->
        <!-- #ifndef MP-WEIXIN -->
        <view class="username-container">
          <view class="username">
            {{ userInfo.nickname || '未设置昵称' }}
          </view>
          <view class="edit-button" @click="openEditModal">
            编辑
          </view>
        </view>
        <!-- #endif -->
        <view class="user-id">
          ID: {{ userInfo.userId || '未知' }}
        </view>
        <view v-if="tokenStore.hasLogin" class="login-status">
          <text class="status-badge">已登录</text>
        </view>
      </view>
    </view>

    <!-- 统计信息卡片 -->
    <view v-if="tokenStore.hasLogin" class="stats-section">
      <!--      <view class="stats-item"> -->
      <!--        <view class="stats-number">0</view> -->
      <!--        <view class="stats-label">订单</view> -->
      <!--      </view> -->
      <!--      <view class="stats-item"> -->
      <!--        <view class="stats-number">0</view> -->
      <!--        <view class="stats-label">收藏</view> -->
      <!--      </view> -->
      <!--      <view class="stats-item"> -->
      <!--        <view class="stats-number">0</view> -->
      <!--        <view class="stats-label">积分</view> -->
      <!--      </view> -->
      <!--      <view class="stats-item"> -->
      <!--        <view class="stats-number">0</view> -->
      <!--        <view class="stats-label">优惠券</view> -->
      <!--      </view> -->
    </view>

    <!-- 功能菜单 -->
    <view v-if="tokenStore.hasLogin" class="menu-section">
      <view
        v-for="(item, index) in menuItems"
        :key="index"
        class="menu-item"
        @click="item.action"
      >
        <view class="menu-icon">
          {{ item.icon }}
        </view>
        <view class="menu-content">
          <view class="menu-title">
            {{ item.title }}
          </view>
          <view class="menu-desc">
            {{ item.desc }}
          </view>
        </view>
        <view class="menu-arrow">
          →
        </view>
      </view>
    </view>

    <!-- 退出登录按钮（仅已登录状态显示） -->
    <view v-if="tokenStore.hasLogin" class="action-section">
      <button type="warn" class="action-button logout-btn" @click="handleLogout">
        退出登录
      </button>
    </view>

    <!-- #ifndef MP-WEIXIN -->
    <!-- 用户信息编辑模态框 -->
    <view v-if="showEditModal" class="modal-overlay" @click="closeEditModal">
      <view class="modal-content" @click.stop>
        <view class="modal-header">
          <text class="modal-title">编辑个人信息</text>
          <view class="modal-close" @click="closeEditModal">
            ×
          </view>
        </view>
        <view class="modal-body">
          <view class="form-item">
            <text class="form-label">昵称</text>
            <input v-model="editForm.nickName" class="form-input" placeholder="请输入昵称">
          </view>
          <view class="form-item">
            <text class="form-label">手机号</text>
            <input v-model="editForm.phonenumber" class="form-input" placeholder="请输入手机号">
          </view>
          <view class="form-item">
            <text class="form-label">性别</text>
            <picker
              :value="editForm.sex"
              :range="['男', '女', '未知']"
              range-key="text"
              @change="(e) => editForm.sex = e.detail.value"
            >
              <view class="form-input">
                {{
                  editForm.sex === '0' ? '男' : editForm.sex === '1' ? '女' : editForm.sex === '2' ? '未知' : '请选择性别'
                }}
              </view>
            </picker>
          </view>
          <view class="form-item">
            <text class="form-label">邮箱</text>
            <input v-model="editForm.email" class="form-input" placeholder="请输入邮箱">
          </view>
        </view>
        <view class="modal-footer">
          <button class="modal-button cancel" @click="closeEditModal">
            取消
          </button>
          <button class="modal-button confirm" @click="saveUserProfile">
            保存
          </button>
        </view>
      </view>
    </view>
    <!-- #endif -->
  </view>
</template>

<style lang="scss" scoped>
/* 基础样式 */
.profile-container {
  min-height: 100vh;
  background-color: #f7f8fa;
  font-family: -apple-system, BlinkMacSystemFont, 'Helvetica Neue', sans-serif;
  overflow-x: hidden;
}

/* 未登录状态样式 */
.login-prompt-container {
  background-color: #f7f8fa;
  padding-bottom: env(safe-area-inset-bottom);
}

.login-content {
  padding: 0;
}

/* 用户头像区域 */
.user-avatar-section {
  background-color: #fff;
  padding: 40rpx;
  margin: 20rpx 30rpx;
  border-radius: 24rpx;
  display: flex;
  align-items: center;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.04);
}

.avatar-wrapper {
  width: 140rpx;
  height: 140rpx;
  border-radius: 50%;
  overflow: hidden;
  margin-right: 40rpx;
  background-color: #f5f5f5;
}

.avatar-img {
  width: 100%;
  height: 100%;
}

.user-info {
  flex: 1;
}

.username-placeholder {
  display: block;
  font-size: 40rpx;
  color: #000;
  font-weight: 400;
  margin-bottom: 12rpx;
}

.user-desc {
  display: block;
  font-size: 26rpx;
  color: #666;
}

/* 功能菜单 */
.menu-list {
  background-color: #fff;
  margin: 20rpx 30rpx;
  border-radius: 24rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.04);
  overflow: hidden;
}

.menu-item-disabled {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 32rpx 40rpx;
  border-bottom: 1rpx solid #f5f5f5;
  opacity: 0.6;
}

.menu-item-disabled:last-child {
  border-bottom: none;
}

.menu-left {
  display: flex;
  align-items: center;
}

.menu-icon {
  font-size: 32rpx;
  margin-right: 24rpx;
  width: 40rpx;
  text-align: center;
}

.menu-title {
  font-size: 30rpx;
  color: #000;
}

.menu-arrow {
  font-size: 28rpx;
  color: #ccc;
}

/* 登录按钮 */
.login-button-container {
  padding: 20rpx 30rpx 40rpx;
}

.clean-login-btn {
  width: 100%;
  height: 88rpx;
  background: linear-gradient(135deg, #1890ff 0%, #096dd9 100%);
  border: none;
  border-radius: 44rpx;
  font-size: 32rpx;
  font-weight: 500;
  color: #fff;
  box-shadow: 0 4rpx 12rpx rgba(24, 144, 255, 0.3);
  transition: all 0.2s ease;
}

.clean-login-btn:active {
  transform: translateY(1rpx);
  box-shadow: 0 2rpx 8rpx rgba(24, 144, 255, 0.3);
}

/* 用户信息区域 */
.user-info-section {
  display: flex;
  align-items: center;
  padding: 40rpx;
  margin: 30rpx 30rpx 20rpx;
  background-color: #fff;
  border-radius: 24rpx;
  box-shadow: 0 6rpx 20rpx rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
}

.avatar-wrapper,
.avatar-button {
  width: 160rpx;
  height: 160rpx;
  margin-right: 40rpx;
  overflow: hidden;
  border: 4rpx solid #f5f5f5;
  border-radius: 50%;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);
  transition: transform 0.2s ease;

  &:hover {
    transform: scale(1.05);
  }
}

.avatar-button {
  padding: 0;
}

.user-details {
  flex: 1;
}

.username-container {
  display: flex;
  align-items: center;
  margin-bottom: 12rpx;
}

.username,
.username-input {
  font-size: 38rpx;
  font-weight: 600;
  color: #333;
  letter-spacing: 0.5rpx;
}

.edit-button {
  margin-left: 20rpx;
  padding: 8rpx 16rpx;
  font-size: 22rpx;
  color: #1890ff;
  background-color: #f0f8ff;
  border-radius: 12rpx;
  cursor: pointer;
  transition: all 0.2s ease;

  &:hover {
    background-color: #e6f7ff;
  }
}

.username-input {
  padding: 0;
  background: none;
  border: none;
  outline: none;
}

.user-id {
  font-size: 28rpx;
  color: #666;
  margin-bottom: 12rpx;
}

.login-status {
  .status-badge {
    display: inline-block;
    padding: 6rpx 16rpx;
    font-size: 22rpx;
    color: #52c41a;
    background-color: #f6ffed;
    border: 1rpx solid #b7eb8f;
    border-radius: 12rpx;
  }
}

/* 统计信息区域 */
.stats-section {
  display: flex;
  background-color: #fff;
  margin: 0 30rpx 20rpx;
  border-radius: 24rpx;
  box-shadow: 0 6rpx 20rpx rgba(0, 0, 0, 0.08);
  overflow: hidden;
}

.stats-item {
  flex: 1;
  text-align: center;
  padding: 30rpx 20rpx;
  position: relative;

  &:not(:last-child)::after {
    content: '';
    position: absolute;
    right: 0;
    top: 20rpx;
    bottom: 20rpx;
    width: 1rpx;
    background-color: #f0f0f0;
  }
}

.stats-number {
  font-size: 32rpx;
  font-weight: 600;
  color: #1890ff;
  margin-bottom: 8rpx;
}

.stats-label {
  font-size: 24rpx;
  color: #666;
}

/* 功能菜单区域 */
.menu-section {
  background-color: #fff;
  margin: 0 30rpx 20rpx;
  border-radius: 24rpx;
  box-shadow: 0 6rpx 20rpx rgba(0, 0, 0, 0.08);
  overflow: hidden;
}

.menu-item {
  display: flex;
  align-items: center;
  padding: 30rpx 40rpx;
  border-bottom: 1rpx solid #f5f5f5;
  transition: background-color 0.2s ease;

  &:last-child {
    border-bottom: none;
  }

  &:hover {
    background-color: #f9f9f9;
  }
}

.menu-icon {
  width: 60rpx;
  font-size: 32rpx;
  text-align: center;
  margin-right: 30rpx;
}

.menu-content {
  flex: 1;
}

.menu-title {
  font-size: 32rpx;
  color: #333;
  margin-bottom: 6rpx;
}

.menu-desc {
  font-size: 24rpx;
  color: #999;
}

.menu-arrow {
  font-size: 24rpx;
  color: #ccc;
  transform: rotate(0deg);
  transition: transform 0.2s ease;
}

.menu-item:active .menu-arrow {
  transform: rotate(90deg);
}

/* 操作按钮区域 */
.action-section {
  margin: 40rpx 30rpx 60rpx;
}

.action-button {
  width: 100%;
  height: 88rpx;
  border-radius: 44rpx;
  font-size: 32rpx;
  font-weight: 600;
  transition: all 0.2s ease;

  &.login-btn {
    background: linear-gradient(135deg, #1890ff 0%, #096dd9 100%);
    box-shadow: 0 8rpx 16rpx rgba(24, 144, 255, 0.3);

    &:hover {
      transform: translateY(-2rpx);
      box-shadow: 0 12rpx 24rpx rgba(24, 144, 255, 0.4);
    }
  }

  &.logout-btn {
    background: linear-gradient(135deg, #ff4d4f 0%, #cf1322 100%);
    box-shadow: 0 8rpx 16rpx rgba(255, 77, 79, 0.3);

    &:hover {
      transform: translateY(-2rpx);
      box-shadow: 0 12rpx 24rpx rgba(255, 77, 79, 0.4);
    }
  }
}

/* 模态框样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 1000;
  display: flex;
  align-items: center;
  justify-content: center;
}

.modal-content {
  width: 80%;
  max-width: 600rpx;
  background-color: #fff;
  border-radius: 24rpx;
  overflow: hidden;
}

.modal-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 40rpx;
  background-color: #f8f9fa;
  border-bottom: 1rpx solid #e9ecef;
}

.modal-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
}

.modal-close {
  font-size: 40rpx;
  color: #999;
  cursor: pointer;

  &:hover {
    color: #333;
  }
}

.modal-body {
  padding: 40rpx;
}

.form-item {
  margin-bottom: 30rpx;

  &:last-child {
    margin-bottom: 0;
  }
}

.form-label {
  display: block;
  margin-bottom: 12rpx;
  font-size: 28rpx;
  color: #333;
  font-weight: 500;
}

.form-input {
  width: 100%;
  padding: 20rpx;
  font-size: 28rpx;
  background-color: #f8f9fa;
  border: 1rpx solid #e9ecef;
  border-radius: 12rpx;
  box-sizing: border-box;

  &:focus {
    border-color: #1890ff;
    background-color: #fff;
  }
}

.modal-footer {
  display: flex;
  gap: 20rpx;
  padding: 30rpx 40rpx 40rpx;
}

.modal-button {
  flex: 1;
  height: 80rpx;
  border-radius: 12rpx;
  font-size: 28rpx;
  font-weight: 500;

  &.cancel {
    background-color: #f5f5f5;
    color: #666;

    &:hover {
      background-color: #e9ecef;
    }
  }

  &.confirm {
    background-color: #1890ff;
    color: #fff;

    &:hover {
      background-color: #0974d9;
    }
  }
}
</style>
